package messageMeServer.manager;

import messageMeTransfer.connection.ServerConnection;
import messageMeTransfer.interfaces.IPackage;
import messageMeTransfer.utilities.PackageWrapper;
import messageMeUtility.interfaces.ICommand;

public class PackageManager extends Thread {

	private ServerConnection connection = null;
	private CommandManager commandManager = null;
	private PackageWrapper packageWrapper = null;

	public PackageManager() {
		this.connection = new ServerConnection();
		this.commandManager = new CommandManager();
		this.packageWrapper = new PackageWrapper();
	}

	public void run() {
		while (true) {
			try {
				IPackage currentPackage = this.connection.recieve();
				if (currentPackage == null)
					continue;

				ICommand currentCommand = this.packageWrapper
						.unwrapPackage(currentPackage);
				if (currentCommand == null)
					continue;

				ICommand answerCommand = this.commandManager
						.executeCommand(currentCommand);
				if (answerCommand == null)
					continue;

				IPackage answerPackage = this.packageWrapper
						.wrapPackage(answerCommand);
				if (answerPackage == null)
					continue;

				this.connection.send(answerPackage, this.connection.getCurrentClient());

			} catch (Exception e) {
			}
		}
	}
}
